﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
using UnityEditor;
namespace AssetBundleHelper{
	public class MD5Tool  {
		public static string GetMD5HashFromFile(string fileName) {
			try {
				FileStream file = new FileStream(fileName, FileMode.Open);
				System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
				byte[] retVal = md5.ComputeHash(file);
				file.Close();

				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < retVal.Length; i++) {
					sb.Append(retVal[i].ToString("x2"));
				}
				return sb.ToString();
			} catch (Exception ex) {
				throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
			}
		}

	}

	public class MD5Window:EditorWindow{
		public List<UnityEngine.Object> objs = new List<UnityEngine.Object>();
		public List<string> md5s = new List<string>();
		[MenuItem("BuildAssetbundle/MD5")]  
		static void Init(){
			GetWindow<MD5Window> ();
		}
		public void OnGUI(){
			
			if (objs.Count == 0 || objs [objs.Count - 1] != null) {
				objs.Add (null);
				md5s.Add ("");
			}
			for (var i = 0; i < objs.Count; i++) {
				if (objs [i] == null && i != objs.Count - 1) {
					objs.RemoveAt (i);
					md5s.RemoveAt (i);
					i--;
					continue;
				}
				GUILayout.BeginHorizontal ();
				objs [i] = EditorGUILayout.ObjectField (objs [i], typeof(UnityEngine.Object));
				GUILayout.Label (md5s [i]);
				GUILayout.EndHorizontal ();
				if (GUI.changed) {
					if (objs [i] == null)
						md5s [i] = "";
					else {
						var path = Application.dataPath.Replace("Assets","")+ AssetDatabase.GetAssetPath (objs [i]);
						md5s[i] = "path:"+path+" md5:"+ MD5Tool.GetMD5HashFromFile (path);
					}
				}
			}
		}
	}
}